<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单的Ajax文件上传</title>
</head>
<body>
<div id="app">
    <h2>简单的Ajax文件上传</h2>
    <div class="file-input">
        <input type="file" id="file" @change="handleFileChange">
    </div>
    <div v-if="uploadFile.filename">
        文件上传成功! 文件名: {{ uploadFile.filename }}; 大小: {{ uploadFile.fileSize }} 字节;
        <a :href="uploadFile.fileUrl" target="_blank" style="margin-right: 6px">查看</a>
        <a :href="uploadFile.fileUrl" download  style="margin-right: 6px">下载</a>

        <a href="javascript:void(0)" @click="deleteFile">删除</a>
    </div>
</div>

<!-- 引入 Vue 和 Axios -->
<script src="/assets/vue/vue3.js"></script>
<script src="/assets/axios/axios.min.js"></script>

<script>
    const {ref, createApp} = Vue;
    // 定义响应式数据
    const uploadFile = ref({filename: ''});
    const app = createApp({
        setup() {
            /**
             * 处理文件选择框变化事件
             * @param {Event} event - 文件选择框的事件对象
             */
            const handleFileChange = (event) => {
                const fileInput = event.target.files[0];
                if (!fileInput) return;

                const formData = new FormData();
                formData.append('file', fileInput);
                axios.post('/api/file/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(response => {
                    // 保存上传的文件信息
                    uploadFile.value = response.data.data;
                    // 每次选择文件后，清空文件输入框的值
                    event.target.value = null;
                })
            }

            /**
             * 删除已上传的文件
             */
            const deleteFile = () => {
                axios.delete(`/api/file/delete/${uploadFile.value.filename}`)
                    .then(response => {
                        if (response.data.code === 200) {
                            // 清空文件信息
                            uploadFile.value = {};
                        } else {
                            alert('文件删除失败: ' + response.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('文件删除失败:', error);
                    });
            }
            return {uploadFile, handleFileChange, deleteFile}
        },
    });
    app.mount('#app'); // 挂载到 DOM
</script>
</body>
</html>